package com.dzm.content.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.dzm.content.config.OssProperties;
import com.dzm.content.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 作者：Dzm
 * 时间：2024-09-13-19:06
 * 功能：
 */

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private OSS ossClient;

    @Override
    public String upload(MultipartFile file) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
//        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        String endpoint = OssProperties.ENDPOINT;
        //获取当前日期
        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        //获取UUID
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //获取文件后缀
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = "default" + "/" + format + "/" + uuid + suffix;

        // 填写Bucket名称，例如examplebucket。
        String bucketName = OssProperties.BUCKET_NAME;

        try {
            InputStream is = file.getInputStream();
            ossClient.putObject(bucketName, objectName, is);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "https://" + bucketName + "." + endpoint + "/" + objectName;
    }
}
